import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import readline
import time
import rlcompleter

## need install python2.7
# pip install paho-mqtt
# pip install readline
#HOST = "cuiyao.top"
from pip._vendor.distlib.compat import raw_input

HOST = "talkie.fchsoft.com"
PORT = 1883
client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
PUBLICTOPIC = "public"


helpstr = "online      :  list  all available device\nconnect     :  connect device 'connect imei'\nexit        :  exit commandline"

CMD = ['online', 'connect', 'exit']
CMDDEVICE = ['help', 'systeminfo', 'install', 'installremote', 'uninstall'
    , 'listapp', 'launch', 'stop', 'listprocess', 'reboot','screenshot','gettvurl','settvurl','disconnect','upgrade', 'exit']

currenttopic = PUBLICTOPIC


def completer(text, state):
    options = [cmd for cmd in CMD if cmd.startswith(text)]
    if state < len(options):
        return options[state]
    else:
        return None

def completerdevice(text, state):
    options = [cmd for cmd in CMDDEVICE if cmd.startswith(text)]
    if state < len(options):
        return options[state]
    else:
        return None

readline.parse_and_bind('tab: complete')
readline.set_completer(completer)

def client_loop():
    client = mqtt.Client(client_id)
    client.username_pw_set("fchsoft", "fchsoft")
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(HOST, PORT, 60)
    client.loop_start()
    print("Please input command:")
    var = 1;

    print("Sessionid:"+client_id)
    global currenttopic
    currenttopic = PUBLICTOPIC
    print("======================================")
    print(helpstr)
    print("======================================")
    while(var == 1):
        command = raw_input()
        if(command=="exit"):
            var=0
        elif(command.startswith("connect")):
            info = command.split(" ")
            if(len(info)>1):
                currenttopic = "devices/"+info[1]
                client.subscribe(currenttopic+client_id+"_r")
                
                print("try to connect "+currenttopic)
                print("======================================")
                print("please wait...")
                readline.set_completer(completerdevice)
                client.publish(currenttopic,"["+client_id +"]"+"connect",0,False)
            else:
                print("command is 'connect imei'")
                print("======================================")
        elif(command == "disconnect"):
            disconnect(client)
        elif(command == "help" and currenttopic==PUBLICTOPIC):
            print(helpstr)
            print("======================================")
        elif(len(command)>1):
            client.publish(currenttopic,"["+client_id +"]"+ command,1,False)

def disconnect(client):
    global currenttopic
    if(currenttopic==PUBLICTOPIC):
        print("No connection is currently available")
        print("======================================")
        return
    print("disconnected "+currenttopic)
    client.unsubscribe(currenttopic+client_id+"_r")
    currenttopic = PUBLICTOPIC
    readline.set_completer(completer)
    print("======================================")
    print(helpstr)
    print("======================================")           

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe(PUBLICTOPIC+client_id+"_r")

def on_message(client, userdata, msg):
    targetmsg = msg.payload.decode("utf-8");
    #msg.topic
    # if(msg.topic==PUBLICTOPIC+"_r"):
    if(targetmsg=="#end"):
        print("================="+msg.topic+"=====================")
    elif(targetmsg=="#disconnect"):
        disconnect(client)
    else:
        print(targetmsg)


if __name__ == '__main__':
    client_loop()
